import 'package:flutter/material.dart';
import 'dart:async';

/// StreamBuilder Demo for counter
///
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(title: 'StreamBuilder Demo - Counter', home: CounterPage());
  }
}

class CounterPage extends StatefulWidget {
  @override
  _CounterPageState createState() => _CounterPageState();
}

class _CounterPageState extends State {
  int _counter = 0;
  final StreamController _streamController = StreamController();

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('StreamBuilder Demo - Counter')),
      body: Center(
        child: StreamBuilder(
            // 监听Stream，每次值改变的时候，更新Text中的内容
            stream: _streamController.stream,
            initialData: _counter,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              return Text('You hit me: ${snapshot.data} times');
            }
          ),
      ),
      floatingActionButton: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.add),
              onPressed: () {
                // 每次点击按钮，更加_counter的值，同时通过Sink将它发送给Stream；
                // 每注入一个值，都会引起StreamBuilder的监听，StreamBuilder重建并刷新counter
                _streamController.sink.add(++_counter);
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 5.0),
            child: FloatingActionButton(
              child: Icon(Icons.remove),
              onPressed: () {
                // 每次点击按钮，更加_counter的值，同时通过Sink将它发送给Stream；
                // 每注入一个值，都会引起StreamBuilder的监听，StreamBuilder重建并刷新counter
                _streamController.sink.add(--_counter);
              },
            ),
          ),
        ],
      ),
    );
  }
}
